package eu.boss.activities;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.map.ObjectMapper;

import Util.FinishListener;
import Util.Util;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import eu.boss.R;
import eu.boss.controller.ShadowStatsController;
import eu.boss.exceptions.LoginException;
import eu.boss.http.Http;
import eu.boss.model.StatsMessage;

/**
 * Splashcreen. If an account is saved, the login is made automatically and
 * FragmentSliderActivity is loaded. Otherwise, loads LoginActivity
 * 
 * @author Arnaud
 * 
 */
public class SplashScreenActivity extends Activity {

	private ShadowStatsController mController;
	private SharedPreferences sharedPreferences;
	private String hash;
	private ServiceConnection mControllerConnection = new ServiceConnection() {
		// Called when the connection with the service is established
		public void onServiceConnected(ComponentName className, IBinder service) {
			mController = ((ShadowStatsController.LocalBinder) service)
					.getService();
			if (Util.isOnline(SplashScreenActivity.this)) {
				sharedPreferences = getSharedPreferences("prefs", MODE_PRIVATE);
				hash = sharedPreferences.getString("hash", null);
				if (hash != null) {
					mController.setHash(hash);
					UserLoginTask ut = new UserLoginTask();
					ut.execute();
				} else {
					new Thread() {
						public void run() {
							try {
								// sleeping thread to see the wonderful
								// splashscreen
								sleep(2000);
							} catch (Exception e) {
							}
							runOnUiThread(new Runnable() {
								public void run() {
									finish();
									startActivity(new Intent(
											SplashScreenActivity.this,
											LoginActivity.class));
								}
							});
						}
					}.start();

				}
			} else
				displayErrorMessageAndFinish(getString(R.string.connection_error));

		}

		// Called when the connection with the service disconnects unexpectedly
		public void onServiceDisconnected(ComponentName className) {
			mController = null;
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splashscreen);
	}

	@Override
	public void onStart() {
		super.onStart();
		// new intent to bind service
		Intent intent = new Intent(this, ShadowStatsController.class);
		this.bindService(intent, mControllerConnection,
				Context.BIND_AUTO_CREATE);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unbindService(mControllerConnection);
	}

	/**
	 * AsyncTask making HTTP post request in a second thread. Login and getting
	 * statsList
	 * 
	 * @author Arnaud
	 * 
	 */
	private class UserLoginTask extends AsyncTask<Void, Void, StatsMessage> {

		String error = null;

		@Override
		protected StatsMessage doInBackground(Void... params) {

			ObjectMapper jacksonMapper = new ObjectMapper();
			StatsMessage statsMsg = null;
			String url = getString(R.string.web_app_url)
					+ getString(R.string.login_url);
			String response = null;
			Http request = new Http();

			try {
				// Creation of a pair Key/Value to put on the server and get
				// response.
				ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
				pairs.add(new BasicNameValuePair("hash", hash));
				response = request.executePostRequest(url, pairs, hash);
				if (response.compareTo("LOGIN ERROR") == 0)
					throw new LoginException(SplashScreenActivity.this);

				statsMsg = jacksonMapper
						.readValue(response, StatsMessage.class);

			} catch (Exception e) {
				error = e.getMessage();
			}

			return statsMsg;
		}

		@Override
		protected void onPostExecute(StatsMessage result) {
			super.onPostExecute(result);
			if (error == null) {
				mController.setStatsMessage(result);
				finish();
				startActivity(new Intent(SplashScreenActivity.this,
						FragmentsSliderActivity.class));
			} else {
				displayErrorMessageAndFinish(error);
			}
		};

	}

	/**
	 * Displaying error message in an AlertDialog and exit activity
	 * 
	 * @param msg
	 *            message to display
	 */
	public void displayErrorMessageAndFinish(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.error));
		builder.setMessage(msg);
		builder.setPositiveButton(R.string.ok, new FinishListener(this));
		builder.show();
	}
}
